import pandas as pd
from scipy.signal import find_peaks
import numpy as np

def clean_and_smooth_data(file_path, output_path, target_peaks, window_length=51, prominence_threshold=0.1, fill_value=0.0):
    """
    清洗并平滑Excel数据，只保留指定峰值，其他峰值设置为指定值。

    Args:
        file_path (str): 输入Excel文件的路径。
        output_path (str): 输出Excel文件的路径。
        target_peaks (list): 需要保留的峰值列表。
        window_length (int): 平滑区域的窗口长度。
        prominence_threshold (float): 峰值检测的显著性阈值。
        fill_value (float): 非目标峰值区域填充的值。
    """
    try:
        df = pd.read_excel(file_path)
    except FileNotFoundError:
        print(f"错误：文件未找到，请检查路径：{file_path}")
        return
    except Exception as e:
        print(f"读取Excel文件时发生错误：{e}")
        return

    if df.empty:
        print("错误：Excel文件为空。")
        return

    column_name = df.columns[0]
    data = df[column_name].values.astype(float)

    # 查找所有峰值
    # 降低prominence_threshold以确保能检测到所有需要处理的峰值
    peaks, properties = find_peaks(data, prominence=prominence_threshold)

    smoothed_data = np.copy(data)

    # 遍历检测到的峰值
    for peak_idx in peaks:
        peak_value = data[peak_idx]
        
        is_target_peak = False
        for target_p in target_peaks:
            if abs(peak_value - target_p) < 1e-5:
                is_target_peak = True
                break
        
        if not is_target_peak:
            # 如果不是目标峰值，则将其周围区域的值设置为fill_value
            start_idx = max(0, peak_idx - window_length // 2)
            end_idx = min(len(data), peak_idx + window_length // 2 + 1)
            
            smoothed_data[start_idx:end_idx] = fill_value

    df[column_name] = smoothed_data

    try:
        df.to_excel(output_path, index=False)
        print(f"数据清洗完成，结果已保存到：{output_path}")
    except Exception as e:
        print(f"保存Excel文件时发生错误：{e}")

if __name__ == "__main__":
    input_excel_path = r"C:\Users\liquanbo\Desktop\新建 XLSX 工作表.xlsx"
    output_excel_path = r"C:\Users\liquanbo\Desktop\清洗后的数据_v3.xlsx" # 保存到新文件，方便比较
    
    target_peaks = [0.65263, 3.60664, 9.37725]

    # 调用函数进行数据处理，使用新的参数和逻辑
    # 窗口长度可以根据实际峰值宽度调整，这里先用51
    clean_and_smooth_data(input_excel_path, output_excel_path, target_peaks, window_length=51, prominence_threshold=0.1, fill_value=0.0)
